package com.ymsoft.myerp.handle;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ymsoft.myerp.entity.User;
import com.ymsoft.myerp.service.IUserService;
import com.ymsoft.myerp.util.GoogleAuthenticator;
import com.ymsoft.myerp.util.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码处理类
 */
@Component
public class VerifyCodeFilterHandler extends OncePerRequestFilter implements InitializingBean {
    /**
     * 登录失败处理器
     */
    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Autowired
    private IUserService iUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 登录接口处理
        if ("POST".equalsIgnoreCase(httpServletRequest.getMethod()) && "/login".equals(httpServletRequest.getServletPath())) {
            String code = httpServletRequest.getParameter("code");
            // 判断验证码是否正确
            if(null == code){
                failureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new ValidateCodeException("验证码不能为空"));
                return;
            }
            // 获取用户名
            String username = httpServletRequest.getParameter("username");
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            User user = iUserService.getOne(queryWrapper);
            if (user == null) {
                failureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new ValidateCodeException("用户名不存在"));
                return;
            }
            // 调用谷歌验证
            // 通过用户获取谷歌商户key
            if (StringUtils.isNotBlank(user.getGoogleKey())) {
                // 判断秘钥是否存在

                // 判断验证码长度
                if(code.length() != 6){
                    failureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new ValidateCodeException("验证码错误"));
                }
                // 秘钥不为空进行谷歌验证
                long t = System.currentTimeMillis();
                GoogleAuthenticator ga = new GoogleAuthenticator();
                ga.setWindowSize(3); // should give 5 * 30 seconds of grace...
                // 传入谷歌商户key 和 验证码
                boolean verifyResult = ga.check_code(user.getGoogleKey(), Long.valueOf(code), t);
                // 验证码不正常，返回
                if (!verifyResult) {
                    failureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new ValidateCodeException("谷歌验证码错误"));
                    return;
                }
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
